package com.andnux.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.andnux.android.MainApp;
import com.andnux.android.adapter.OnItemClickListener;
import com.andnux.android.adapter.WorksAdapter;
import com.andnux.android.data.PageData;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.data.Works;
import com.andnux.android.databinding.ActivitySearchBinding;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class SearchActivity extends BaseActivity<ActivitySearchBinding> {

    private int current = 0;
    private static final int size = 10;
    private WorksAdapter adapter;
    private final List<Works> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        binding.search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                binding.clear.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.search.setText("");
                loadData();
            }
        });
        binding.search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                loadData();
                return true;
            }
        });

        binding.btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData();
            }
        });

        adapter = new WorksAdapter();
        adapter.setOnItemClickListener(new OnItemClickListener<com.andnux.android.databinding.ItemWorksBinding>() {
            @Override
            public void onItemClick(com.andnux.android.databinding.ItemWorksBinding view, int position, long id) {
                Intent intent = new Intent(SearchActivity.this, WorksDetailsActivity.class);
                intent.putExtra("works", list.get(position));
                startActivity(intent);
            }
        });
        binding.smart.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                current++;
                loadData();
            }

            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                current = 0;
                loadData();
            }
        });
        binding.content.setAdapter(adapter);
        loadData();
    }

    private void loadData() {
        DesignCloudApi api = RetrofitClient.getInstance().getServerApi();
        SystemUsers users = MainApp.getApp().getSystemUsers();
        String lx = "";
        if (users != null) {
            String role = users.getRole();
            if ("1".contentEquals(role)) {
                lx = "0";
            } else {
                lx = "1";
            }
        }
        String search = binding.search.getText().toString();
        addDisposable(api.worksPage(current, size, lx, search, "", 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<PageData<List<Works>>>>() {
                    @Override
                    public void onSuccess(Result<PageData<List<Works>>> result) {
                        if (current == 0) {
                            list.clear();
                        }
                        List<Works> works = result.getData().getList();
                        list.addAll(works);
                        adapter.setNewData(list);
                        if (works.size() < size) {
                            binding.smart.finishLoadMoreWithNoMoreData();
                        } else {
                            binding.smart.finishLoadMore();
                        }
                        binding.smart.finishRefresh();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        binding.smart.finishLoadMoreWithNoMoreData();
                        binding.smart.finishRefresh();
                        if (throwable != null) {
                            Toast.makeText(SearchActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));

    }
}